package com.sinacom.ibuilding.action;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.Role;
import com.sinacom.ibuilding.service.MemberService;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.ExcelReader;
import com.sinacom.ibuilding.util.PageModel;




public class MemberAction {
	
	private MemberService memberService = new MemberService();
	private int page = 1;
	private PageModel pageModel;
	private Member member;
	private String id;
	
	private List roleList;
	private File userfile;
	private String userfileFileName;
	private String userfileContentType;
	
	private Role role;
	private List roleTree;
	
	private String search;
	private String searchRole;
	private String roleId;
	private String oldRoleId;
	public String list()throws Exception{
	    HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
            pageModel = memberService.getMembers(page);
            List mList = pageModel.getList();
            if(mList!= null && mList.size() > 0){
                for (int i = 0; i < mList.size(); i++) {
                    Member m = (Member) mList.get(i);
                    if(m != null){
                        m.setRole(memberService.getRoleById(m.getRoleId()));
                    }
                }   
            }
            
            return "list";
        }else{
            return "error";
        }
		
	}
	
	public String userList()throws Exception{
	    HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
        	roleTree = (List) Constants.cacheMap.get("roleTree");
            pageModel = memberService.getMembers(search,searchRole,page);
            List mList = pageModel.getList(); 
            if(mList!= null && mList.size() > 0){
                for (int i = 0; i < mList.size(); i++) {
                    Member m = (Member) mList.get(i);
                    if(m != null){
                        m.setRole(memberService.getRoleById(m.getRoleId()));
                    }
                }   
            }
            
            return "userList";
        }else{
            return "error";
        }
	}
	
	public String loadUser()throws Exception{
	    HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
        	roleTree = (List) Constants.cacheMap.get("roleTree");
            pageModel = memberService.getMembers(search,searchRole,page); 
            List mList = pageModel.getList();
            if(mList!= null && mList.size() > 0){
                for (int i = 0; i < mList.size(); i++) {
                    Member m = (Member) mList.get(i);
                    if(m != null){
                        m.setRole(memberService.getRoleById(m.getRoleId()));
                    }
                }   
            }
            
            return "loadUser";
        }else{
            return "error";
        }
		
	}
	
	public String add()throws Exception{
	    HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
            roleList = memberService.getRole();
            return "input";
        }else{
            return "error";
        }
    }
	
	public String edit()throws Exception{
	    HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang()!=null && role.getUserMang().booleanValue()){
            roleList = memberService.getRole();
            member = memberService.getMemberById(id);
            if(member != null){
                member.setRole(memberService.getRoleById(member.getRoleId()));
            }
            return "input";
        }else{
            return "error";
        }
	}
	
	public String save()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
            if(StringUtils.isEmpty(member.getPassword()) && StringUtils.isEmpty(member.getId())) member.setPassword("11111111");
            if(!StringUtils.isEmpty(member.getPassword())){
                member.setPassword(DigestUtils.md5Hex(member.getPassword()));   
            }
            Map map = new HashMap();  
            boolean b = memberService.saveMember(member);
            
            
            if(b){
                map.put("success", "true");
                map.put("msg", "会员添加修改成功");
                pw.print(JSONObject.fromObject(map));
                
            }else{
                map.put("success", "false");
                map.put("msg", "会员添加修改失败");
                pw.print(JSONObject.fromObject(map));
            }
            return null;
           
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
    }
	
	public String editUser()throws Exception{ 
		if(!StringUtils.isEmpty(id)){
			member = memberService.getMemberById(id);
		} 
		HttpServletRequest request = ServletActionContext.getRequest();
		 request.setAttribute("user", member);
        return "editUser";
	}
	public String saveEditUser()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null; 
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
            
            Map map = new HashMap();  
            if(memberService.updateMember(member)){
        		map.put("success", "true");
    	        map.put("msg", "修改用户成功");
    	        pw.print(JSONObject.fromObject(map));
    	        return null;
        	}else{
        		map.put("success", "true");
    	        map.put("msg", "修改用户失败");
    	        pw.print(JSONObject.fromObject(map));
    	        return null;
        	}
                
           
            
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
    }
	public String saveUser()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null; 
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
        	if(member != null && StringUtils.isEmpty(member.getId())){
        		member.setPassword(DigestUtils.md5Hex(Constants.PASSWORD_DEF));
        	}
            
            Map map = new HashMap();  
            boolean addEdit = StringUtils.isEmpty(member.getId());
            boolean b = memberService.saveMember(member); 
            
            
            if(b){
                map.put("success", "true");
                if(addEdit){
                	map.put("msg", "会员添加成功");
                }else{
                	map.put("msg", "会员修改成功");
                }
                
                pw.print(JSONObject.fromObject(map));
                
            }else{
                map.put("success", "false");
                if(StringUtils.isEmpty(member.getId())){
                	map.put("msg", "会员添加失败");
                }else{
                	map.put("msg", "会员修改失败");
                }
                pw.print(JSONObject.fromObject(map));
            }
            return null;
           
            
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
    }
	
	public String moveMember()throws Exception{
	    HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null; 
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
        	Map map = new HashMap();
           memberService.deleteMemberRole(member.getId(), oldRoleId); 
           memberService.insertMemberRole(member.getId(), member.getRoleId());
            
            map.put("success", "true");
            map.put("msg", "移动成功");
            
            pw.print(JSONObject.fromObject(map));
                
            return null;
           
            
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
    }
	
	public String resetPwd()throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole(); 
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
        	member.setPassword(DigestUtils.md5Hex(Constants.PASSWORD_DEF));
            
            Map map = new HashMap();  
            member.setLogined(new Boolean(false));
            boolean b = memberService.updateMember(member);
            
            
            if(b){
                map.put("success", "true");
                map.put("msg", "重设密码成功");
                pw.print(JSONObject.fromObject(map));
                
            }else{
                map.put("success", "false");
                map.put("msg", "重设密码失败");
                pw.print(JSONObject.fromObject(map));
            }
            return null;
           
            
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
	}
	
	public String deleteUser()throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){  
            
            Map map = new HashMap();  
            boolean b = memberService.deleteMember(id);
            
            
            if(b){
                map.put("success", "true");
                map.put("msg", "删除用户成功");
                pw.print(JSONObject.fromObject(map));
                
            }else{
                map.put("success", "false");
                map.put("msg", "删除用户失败");
                pw.print(JSONObject.fromObject(map));
            }
            return null;
           
            
        }else{
            Map map = new HashMap();  
            map.put("success", "false");
            map.put("msg", "您没有管理权限");
            pw.print(JSONObject.fromObject(map));
            return "error";
        }
	}
	
	public String delete()throws Exception{
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
            memberService.deleteMember(id);
            HttpServletResponse response = ServletActionContext.getResponse();
            response.sendRedirect("member!list.do");
            return null;
        }else{
            return "error";
        }
    }
	
	public String updatepwd()throws Exception{
        HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang().booleanValue()){
            memberService.deleteMember(id);
            HttpServletResponse response = ServletActionContext.getResponse();
            response.sendRedirect("member!list.do");
            return null;
        }else{
            return "error";
        }
    }
	public String createRole()throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null; 
        pw = response.getWriter();
        Map map = new HashMap();
        try{
        	memberService.createRole(role);
        	Constants.cacheMap.put("roleTree", memberService.getRoleTree("0"));
        	Constants.roleMap.put(role.getId(), role.getName());
        	map.put("success", "true");
            map.put("msg", "新建分组成功");
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", "false");
            map.put("msg", "新建分组失败");
        }
        
        
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	public String renameRole()throws Exception{
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        try{
        	memberService.updateRole(role); 
        	Constants.cacheMap.put("roleTree", memberService.getRoleTree("0"));
        	Constants.roleMap.put(role.getId(), role.getName()); 
        	map.put("success", "true");
            map.put("msg", "修改名称成功");
        }catch(Exception e){
        	map.put("success", "false");
            map.put("msg", "修改名称失败");
        }
        
        
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	
	public String editRole()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
        Member loginMember = (Member) request.getSession().getAttribute("member");
        Role role = loginMember.getRole();
        if(role.getUserMang() != null && role.getUserMang().booleanValue()){
//        	roleTree = memberService.getRoleTree("0");
        	roleTree = (List) Constants.cacheMap.get("roleTree");
    		return "editRole";
        }else{
        	return "error";
        }
		
	}
	
	public String editRoleRight()throws Exception{
		if(StringUtils.isEmpty(id)) id = "1";
		role = memberService.getRoleById(id); 
		return "editRoleRight";
	}
	
	public String saveRole()throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        try{
        	memberService.updateRole(role); 
        	Constants.cacheMap.put("roleTree", memberService.getRoleTree("0"));
        	map.put("success", "true");
            map.put("msg", "授权成功");
        }catch(Exception e){
        	map.put("success", "false");
            map.put("msg", "授权失败");
        }
        
        
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String deleteRole()throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        try{
        	if(!StringUtils.isEmpty(roleId) && ("1".equals(roleId) || "2".equals(roleId) || "3".equals(roleId))){
        		map.put("success", "false"); 
                map.put("msg", "根节点不能删除");
        		pw.print(JSONObject.fromObject(map));
        		 return null;
        	}
        	List list = memberService.getMemberByRole(roleId); 
        	if(list != null && list.size() > 0){ 
        		map.put("success", "false");
                map.put("msg", "分组下有用户，不能删除该分组");
        	}else{
        		memberService.deleteRole(roleId);
        		Constants.cacheMap.put("roleTree", memberService.getRoleTree("0"));
        		Constants.roleMap.remove(roleId);
            	map.put("success", "true");
                map.put("msg", "删除组成功");
        	}
        	
        }catch(Exception e){
        	map.put("success", "false");
            map.put("msg", "删除组失败");
        }
        
        
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	public String moveOutMember()throws Exception{
		
		HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        try{
    		memberService.deleteMemberRole(id,roleId);
        	map.put("success", "true");
            map.put("msg", "移除用户成功");
        	
        }catch(Exception e){
        	map.put("success", "false");
            map.put("msg", "删除组失败");
        }
        
        
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	//上传用户的excel文件
	public String userfile()throws Exception{
		ExcelReader excelReader = new ExcelReader(userfile); 
		List userlist = excelReader.getAllData(0);
		if(userlist != null && userlist.size() > 0){ 
			
			for (int i = 0; i < userlist.size(); i++) {
				if(i != 0){
					String[] str = (String[]) userlist.get(i);
					if(str != null && str.length > 0){
						Member member = new Member();
						member.setPassword(DigestUtils.md5Hex(Constants.PASSWORD_DEF));
						for (int j = 0; j < str.length; j++) {
							switch(j){
								case 0:{
		//							member.setId(str);
									member.setSchoolCode(str[j]);
									break;
								}
								case 1:{
									member.setUsername(str[j]);
									break;
								}
								case 2:{
									member.setMobile(str[j]);
									break;
								}
								case 3:{
									member.setSchoolName(str[j]);
									break;
								}
								case 4:{
									member.setEmail(str[j]);
									break;
								}
								case 5:{
									member.setRoleId(str[j]);
									break;
								}
								default:{
									break;
								}
							}
							
						}
						if(StringUtils.isEmpty(member.getRoleId())){
							member.setRoleId(roleId);
						}
						memberService.saveMember(member);
					}
				}
				
				
				
			}
		}
        
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        pw = response.getWriter();
        Map map = new HashMap();
        map.put("success", "true");
        map.put("msg", "用户上传成功");
        pw.print(JSONObject.fromObject(map));
		return null;
	}
	
	
	public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public PageModel getPageModel() {
        return pageModel;
    }

    public void setPageModel(PageModel pageModel) {
        this.pageModel = pageModel;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    

    public List getRoleList() {
        return roleList;
    }

    public void setRoleList(List roleList) {
        this.roleList = roleList;
    }
    

    public File getUserfile() {
		return userfile;
	}

	public void setUserfile(File userfile) {
		this.userfile = userfile;
	}

	public String getUserfileFileName() {
		return userfileFileName;
	}

	public void setUserfileFileName(String userfileFileName) {
		this.userfileFileName = userfileFileName;
	}

	public String getUserfileContentType() {
		return userfileContentType;
	}

	public void setUserfileContentType(String userfileContentType) {
		this.userfileContentType = userfileContentType;
	}

	
	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	

	public List getRoleTree() {
		return roleTree;
	}

	public void setRoleTree(List roleTree) {
		this.roleTree = roleTree;
	}
	
	

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getSearchRole() {
		return searchRole;
	}

	public void setSearchRole(String searchRole) {
		this.searchRole = searchRole;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	
	public String getOldRoleId() {
		return oldRoleId;
	}

	public void setOldRoleId(String oldRoleId) {
		this.oldRoleId = oldRoleId;
	}

	public static void main(String[] args) {
		System.out.println(DigestUtils.md5Hex("111111"));
	}
	
	
}
